package com.syl.upimg.service.impl;

import com.syl.upimg.bean.JdBean;
import com.syl.upimg.enums.ImageUploadTypeEnum;
import com.syl.upimg.service.BaseUpload;
import com.syl.upimg.utils.ImageUtils;
import com.syl.upimg.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 京东羊毛 已失效
 *
 * @author syl
 * @create 2019-08-02 12:06
 **/
@Service
public class JdFleece implements BaseUpload {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public RestTemplate createRestTemplate() {
        return restTemplate;
    }

    @Override
    public LinkedMultiValueMap<String, Object> getParam(FileSystemResource file, String fileName, String fileType) {
        LinkedMultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("aid", "undefined");
        multiValueMap.add("appId", "undefined");
        multiValueMap.add("pin", "undefined");
        multiValueMap.add("clientType", "wh5");
        multiValueMap.add("s", ImageUtils.imageToDataBase64(file.getPath()));
        return multiValueMap;
    }

    public HttpHeaders getDefaultHeader() {
        HttpHeaders defaultHeader = getDefaultHeader(
            "https://jdcs.jd.com", "https://jdcs.jd.com/jdchat/custom.action?entry=jd_fwztc");
        defaultHeader.add("Accept", "application/json, text/plain, */*");
        defaultHeader.add("Upgrade-insecure-requests", "1");
        return defaultHeader;
    }

    @Override
    public String[] getLimit() {
        return new String[]{"jpg", "png", "bmp"};
    }

    @Override
    public String getUrl() {
        return "https://imio.jd.com/uploadfile/file/post.do";
    }

    public JdBean upload(String filePath) throws IOException {
        return this.upload(filePath, false);
    }

    public JdBean upload(String filePath, boolean delete) throws IOException {
        long startTime = System.currentTimeMillis();
        String html = this.uploadByString(filePath, delete);
        if (StringUtils.isEmpty(html)) return null;
        String json = html.replace("<html><script type=\"text/javascript\">document.domain=\"jd.com\";</script><body>", "").replace("</body></html>", "");
        if (StringUtils.isEmpty(json)) return null;
        JdBean jdBean = JsonUtils.fromJson(json, JdBean.class);
        long endTime = System.currentTimeMillis();
        int intValue = new Long(endTime - startTime).intValue();
        jdBean.setBaseUrl(jdBean.getPath());
        jdBean.setTimerMs(intValue).setImageUploadTypeEnum(ImageUploadTypeEnum.JD);
        return jdBean;
    }

}
